package com.zhn.evsi.controller.Evsi;

import cn.hutool.core.util.StrUtil;
import com.zhn.evsi.common.Result;
import com.zhn.evsi.domain.entity.evsi.EvsiAuthToken;
import com.zhn.evsi.exception.CustomException;
import com.zhn.evsi.service.IEvsiAuthTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 授权验证，获取token
 * */
@Api(tags = "授权验证")
@ApiSort(value = 1)
@Slf4j
@RestController
@RequestMapping("/oauth")
public class EvsiAuthTokenController {

    @Autowired
    private IEvsiAuthTokenService authTokenService;

    /**
     * 拼接url并返回给前端
     * https://{login server base url}/oauth/authorize?response_type={response type}&redirect_uri={redirect uri}&client_id={client id}&scope={scopes}&state={state}
     * */
    @ApiOperation("返回授权地址")
    @ApiOperationSupport(order = 1)
    @GetMapping("/geturl")
    public Result getUrl() {
        String url = authTokenService.getUrl();
        return Result.success(url);
    }

    /**
     * 回调获取code，并发送请求，存放到redis，并持久化保存
     * */
    @ApiOperation("获取回调code")
    @ApiOperationSupport(order = 2)
    @GetMapping("/token")
    public Result oauthToken(@RequestParam("code")  String code) {
        if (StrUtil.isBlank(code)) {
            throw new CustomException("code没有获取到");
        }
        // TODO 获取当前登录用户的角色信息，并随着oauthToken方法传参
        String email = "1085155177@qq.com";
        authTokenService.oauthToken(code, email);
        return Result.success();
    }

    // 查询授权信息
    @ApiOperation("查询授权信息")
    @ApiOperationSupport(order = 3)
    @GetMapping("/list")
    public Result oauthTokenList(@RequestParam(defaultValue = "") String mail) {
        List<EvsiAuthToken> evsiAuthTokens = authTokenService.oauthTokenList(mail);
        return Result.success(evsiAuthTokens);
    }
}
